#include "requesthandlerthreadpool.h"
#include "requesthandlerthread.h"

RequestHandlerThreadPool *RequestHandlerThreadPool::m_instance=0;

QMutex RequestHandlerThreadPool::m_mutex;

RequestHandlerThreadPool::RequestHandlerThreadPool()
{
    if(m_runningThreadList == NULL)
    {

        m_runningThreadList = new QList<RequestHandlerThread*>();
    }

    purgeStopThread();
}

RequestHandlerThreadPool::~RequestHandlerThreadPool()
{

    int i = 0;
    if(m_runningThreadList != NULL)
    {
        if(!m_runningThreadList->isEmpty())
        {
            for(i = 0; i<m_runningThreadList->size(); ++i)
            {
                delete m_runningThreadList->at(i);
            }

            m_runningThreadList->clear();
        }
    }
    if(m_purgeThread != NULL)
    {
        m_purgeThread->setStop(true);
        delete m_purgeThread;
    }
}

void RequestHandlerThreadPool::purgeStopThread()
{
    m_purgeThread = new PurgeHandlerThread2();
    m_purgeThread->start();
}

int RequestHandlerThreadPool::addHandlerThread(RequestHandlerThread* thread)
{
    QMutexLocker locker(&m_mutex);

    if((m_runningThreadList == NULL) || (thread == NULL) )
    {
        return -1;
    }

    m_runningThreadList->push_back(thread);

}

int RequestHandlerThreadPool::removeHandlerThread(RequestHandlerThread* thread)
{
    QMutexLocker locker(&m_mutex);

    if((m_runningThreadList == NULL) || (thread == NULL) )
    {
        return -1;
    }

    m_runningThreadList->removeOne(thread);
    delete thread;
}

RequestHandlerThread *RequestHandlerThreadPool::getHandlerThread(const std::string request_id)
{
    if((m_runningThreadList != NULL) && (m_runningThreadList->isEmpty()))
    {
        for(int i = 0; i < m_runningThreadList->size(); ++i)
        {
            if(request_id == m_runningThreadList->at(i)->getRequestID())
            {
                return m_runningThreadList->at(i);
            }
        }
    }

    return NULL;
}

PurgeHandlerThread2::PurgeHandlerThread2()
{
    m_stop = true;
}

PurgeHandlerThread2::~PurgeHandlerThread2()
{
    m_stop = false;
}

void PurgeHandlerThread2::run()
{
    QList<RequestHandlerThread*> *list;
    int i = 0;
    while(m_stop)
    {
        list = RequestHandlerThreadPool::getInstance()->getThreadList();
        for(i = 0; i < list->size(); ++i)
        {
            if(list->at(i)->isFinished())
            {
                RequestHandlerThreadPool::getInstance()->removeHandlerThread(list->at(i));
            }
        }

        QThread::sleep(5);
    }


}
